<!DOCTYPE html><html class="theme-next gemini use-motion" lang="zh-CN"><head><meta name="generator" content="Hexo 3.9.0"><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=2"><meta name="theme-color" content="#222"><link rel="apple-touch-icon" sizes="180x180" href="/favicon.ico?v=6.7.0"><link rel="icon" type="image/png" sizes="32x32" href="/favicon.ico?v=6.7.0"><link rel="icon" type="image/png" sizes="16x16" href="/favicon.ico?v=6.7.0"><script id="hexo.configurations">var NexT=window.NexT||{},CONFIG={root:"/",scheme:"Gemini",version:"6.7.0",sidebar:{position:"left",display:"post",offset:12,b2t:!1,scrollpercent:!1,onmobile:!1},fancybox:!0,fastclick:!0,lazyload:!1,tabs:!0,motion:{enable:!0,async:!1,transition:{post_block:"fadeIn",post_header:"slideDownIn",post_body:"slideDownIn",coll_header:"slideLeftIn",sidebar:"slideUpIn"}},algolia:{applicationID:"",apiKey:"",indexName:"",hits:{per_page:10},labels:{input_placeholder:"Search for Posts",hits_empty:"We didn't find any results for the search: ${query}",hits_stats:"${hits} results found in ${time} ms"}}}</script><meta name="description" content="最近使用 Go 开发了一个新服务，第一次使用 Go 进行企业级服务开发，特总结经验如下。"><meta name="keywords" content="Go"><meta property="og:type" content="article"><meta property="og:title" content="Go 开发经验总结"><meta property="og:url" content="http://moeyui.cn/开发/a1eba719.html"><meta property="og:site_name" content="不是很懂"><meta property="og:description" content="最近使用 Go 开发了一个新服务，第一次使用 Go 进行企业级服务开发，特总结经验如下。"><meta property="og:locale" content="zh-CN"><meta property="og:image" content="https://box.kancloud.cn/2016-01-10_5691fbe34a76f.png"><meta property="og:image" content="https://pic2.zhimg.com/80/v2-ae1d48089f6a4ff589bb5b948ee74a8d_1440w.jpg"><meta property="og:image" content="https://pic4.zhimg.com/80/v2-a31ca547de92311f644a4d25566eca1f_1440w.jpg"><meta property="og:image" content="https://images2018.cnblogs.com/blog/1075473/201807/1075473-20180704144900055-654632620.jpg"><meta property="og:image" content="https://images2018.cnblogs.com/blog/1075473/201807/1075473-20180704160300058-287296807.jpg"><meta property="og:image" content="https://images2018.cnblogs.com/blog/1075473/201807/1075473-20180704162532330-809705926.jpg"><meta property="og:image" content="https://images2018.cnblogs.com/blog/1075473/201807/1075473-20180704164251684-1689850867.jpg"><meta property="og:image" content="https://oscimg.oschina.net/oscnet/3d44fe27957013aa82eca2923cafe50d909.jpg"><meta property="og:image" content="https://img-blog.csdnimg.cn/20190307092857857.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3UwMTA4NTMyNjE=,size_16,color_FFFFFF,t_70"><meta property="og:image" content="https://img-blog.csdnimg.cn/20190105122332181.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3UwMTA4NTMyNjE=,size_16,color_FFFFFF,t_70"><meta property="og:image" content="https://img-blog.csdnimg.cn/20190105123351626.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3UwMTA4NTMyNjE=,size_16,color_FFFFFF,t_70"><meta property="og:image" content="https://img-blog.csdnimg.cn/20190105123802359.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3UwMTA4NTMyNjE=,size_16,color_FFFFFF,t_70"><meta property="og:image" content="https://img-blog.csdnimg.cn/20190105143018955.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3UwMTA4NTMyNjE=,size_16,color_FFFFFF,t_70"><meta property="og:image" content="https://img-blog.csdnimg.cn/20190307093911177.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3UwMTA4NTMyNjE=,size_16,color_FFFFFF,t_70"><meta property="og:image" content="https://i6448038.github.io/img/channel/hchan.png"><meta property="og:image" content="https://tva1.sinaimg.cn/large/00831rSTgy1gd7c035gouj30xc0aa74l.jpg"><meta property="og:image" content="https://tva1.sinaimg.cn/large/00831rSTgy1gd7c1p9jmij30xc0aadfz.jpg"><meta property="og:updated_time" content="2020-04-20T14:58:34.610Z"><meta name="twitter:card" content="summary"><meta name="twitter:title" content="Go 开发经验总结"><meta name="twitter:description" content="最近使用 Go 开发了一个新服务，第一次使用 Go 进行企业级服务开发，特总结经验如下。"><meta name="twitter:image" content="https://box.kancloud.cn/2016-01-10_5691fbe34a76f.png"><link rel="alternate" href="/atom.xml" title="不是很懂" type="application/atom+xml"><link rel="canonical" href="http://moeyui.cn/开发/a1eba719.html"><script id="page.configurations">CONFIG.page={sidebar:""}</script><title>Go 开发经验总结 | 不是很懂</title><script async="" src="//www.googletagmanager.com/gtag/js?id=UA-75483578-1"></script><script>function gtag(){dataLayer.push(arguments)}window.dataLayer=window.dataLayer||[],gtag("js",new Date),gtag("config","UA-75483578-1")</script><noscript><style>.sidebar-inner,.use-motion .brand,.use-motion .collection-title,.use-motion .comments,.use-motion .menu-item,.use-motion .motion-element,.use-motion .pagination,.use-motion .post-block,.use-motion .post-body,.use-motion .post-header{opacity:initial}.use-motion .logo,.use-motion .site-subtitle,.use-motion .site-title{opacity:initial;top:initial}.use-motion .logo-line-before i{left:initial}.use-motion .logo-line-after i{right:initial}</style></noscript><script>function loadCss(e){var t=document,s=t.head,n=t.createElement("link");n.rel="stylesheet",n.href=e,function e(s){if(t.body)return s();setTimeout(function(){e(s)})}(function(){s.appendChild(n)})}loadCss("/style.css"),loadCss("https://cdn.staticfile.org/font-awesome/4.6.2/css/font-awesome.min.css")</script><noscript><link rel="stylesheet" href="/style.css"><link rel="stylesheet" href="https://cdn.staticfile.org/font-awesome/4.6.2/css/font-awesome.min.css"></noscript></head><body itemscope="" itemtype="http://schema.org/WebPage" lang="zh-CN"><div class="container sidebar-position-left page-post-detail"><div class="headband"></div><header id="header" class="header" itemscope="" itemtype="http://schema.org/WPHeader"><div class="header-inner"><div class="site-brand-wrapper"><div class="site-meta"><div class="custom-logo-site-title"><a href="/" class="brand" rel="start"><span class="logo-line-before"><i></i></span> <span class="site-title">不是很懂</span><span class="logo-line-after"><i></i></span></a></div><h1 class="site-subtitle" itemprop="description">不是很懂你们程序员</h1></div><div class="site-nav-toggle"> <button aria-label="切换导航栏"><span class="btn-bar"></span><span class="btn-bar"></span><span class="btn-bar"></span></button></div></div><nav class="site-nav"><ul id="menu" class="menu"><li class="menu-item menu-item-home"><a href="/" rel="section"><i class="menu-item-icon fa fa-fw fa-home"></i><br>首页</a></li><li class="menu-item menu-item-about"><a href="/about/" rel="section"><i class="menu-item-icon fa fa-fw fa-user"></i><br>关于</a></li><li class="menu-item menu-item-tags"><a href="/tags/" rel="section"><i class="menu-item-icon fa fa-fw fa-tags"></i><br>标签</a></li><li class="menu-item menu-item-categories"><a href="/categories/" rel="section"><i class="menu-item-icon fa fa-fw fa-th"></i><br>分类</a></li><li class="menu-item menu-item-archives"><a href="/archives/" rel="section"><i class="menu-item-icon fa fa-fw fa-archive"></i><br>归档</a></li></ul></nav></div></header> <a href="https://github.com/moeyui1" class="github-corner" title="Follow me on GitHub" aria-label="Follow me on GitHub" rel="noopener" target="_blank"><svg width="80" height="80" viewBox="0 0 250 250" style="fill:#222;color:#fff;position:absolute;top:0;border:0;right:0" aria-hidden="true"><path d="M0 0 115 115 130 115 142 142 250 250 250 0Z"></path><path d="M128.3 109C113.8 99.7 119 89.6 119 89.6 122 82.7 120.5 78.6 120.5 78.6 119.2 72 123.4 76.3 123.4 76.3 127.3 80.9 125.5 87.3 125.5 87.3 122.9 97.6 130.6 101.9 134.4 103.2" fill="currentColor" style="transform-origin:130px 106px" class="octo-arm"></path><path d="M115 115C114.9 115.1 118.7 116.5 119.8 115.4L133.7 101.6C136.9 99.2 139.9 98.4 142.2 98.6 133.8 88 127.5 74.4 143.8 58 148.5 53.4 154 51.2 159.7 51 160.3 49.4 163.2 43.6 171.4 40.1 171.4 40.1 176.1 42.5 178.8 56.2 183.1 58.6 187.2 61.8 190.9 65.4 194.5 69 197.7 73.2 200.1 77.6 213.8 80.2 216.3 84.9 216.3 84.9 212.7 93.1 206.9 96 205.4 96.6 205.1 102.4 203 107.8 198.3 112.5 181.9 128.9 168.3 122.5 157.7 114.1 157.9 116.9 156.7 120.9 152.7 124.9L141 136.5C139.8 137.7 141.6 141.9 141.8 141.8Z" fill="currentColor" class="octo-body"></path></svg></a><main id="main" class="main"><div class="main-inner"><div class="content-wrap"><div id="content" class="content"><div id="posts" class="posts-expand"><article class="post post-type-normal" itemscope="" itemtype="http://schema.org/Article"><div class="post-block"><link itemprop="mainEntityOfPage" href="http://moeyui.cn/开发/a1eba719.html"><span hidden="" itemprop="author" itemscope="" itemtype="http://schema.org/Person"><meta itemprop="name" content="moeyui"><meta itemprop="description" content="moeyui | moeyui's blog"><meta itemprop="image" content="/images/blogAvatar.jpg"></span><span hidden="" itemprop="publisher" itemscope="" itemtype="http://schema.org/Organization"><meta itemprop="name" content="不是很懂"></span><header class="post-header"><h2 class="post-title" itemprop="name headline">Go 开发经验总结</h2><div class="post-meta"><span class="post-time"><span class="post-meta-item-icon"><i class="fa fa-calendar-o"></i></span> <span class="post-meta-item-text">发表于</span> <time title="创建时间：2020-04-20 22:55:01 / 修改时间：22:58:34" itemprop="dateCreated datePublished" datetime="2020-04-20T22:55:01+08:00">2020-04-20</time></span> <span class="post-category"><span class="post-meta-divider">|</span><span class="post-meta-item-icon"><i class="fa fa-folder-o"></i></span> <span class="post-meta-item-text">分类于</span> <span itemprop="about" itemscope="" itemtype="http://schema.org/Thing"><a href="/categories/开发/" itemprop="url" rel="index"><span itemprop="name">开发</span></a></span></span> <span class="post-comments-count"><span class="post-meta-divider">|</span><span class="post-meta-item-icon"><i class="fa fa-comment-o"></i></span> <a href="/开发/a1eba719.html#comments" itemprop="discussionUrl"><span class="post-meta-item-text">评论数：</span><span class="post-comments-count valine-comment-count" data-xid="/开发/a1eba719.html" itemprop="commentCount"></span></a></span> <span id="/开发/a1eba719.html" class="leancloud_visitors" data-flag-title="Go 开发经验总结"><span class="post-meta-divider">|</span><span class="post-meta-item-icon"><i class="fa fa-eye"></i></span> <span class="post-meta-item-text">阅读次数：</span><span class="leancloud-visitors-count"></span></span><div class="post-description">最近使用 Go 开发了一个新服务，第一次使用 Go 进行企业级服务开发，特总结经验如下。</div></div></header><div class="post-body" itemprop="articleBody"><h2 id="1-简介"><a href="#1-简介" class="headerlink" title="1.简介"></a>1.简介</h2><p>Go语言有时候被描述为“C类似语言”，或者是“21世纪的C语言”。Go 从 C 语言继承了相似的表达式语法、控制流结构、基础数据类型、调用参数传值、指针等很多思想，还有C语言一直所看中的编译后机器码的运行效率以及和现有操作系统的无缝适配。</p><p>Go 虽然拥有自动垃圾回收、一等函数、词法作用域、系统调用接口等非常棒的特性，但其本身的特性并不多，并且也不太可能添加太多的特性。例如，Go 没有隐式的数值转换，没有构造函数和析构函数，没有运算符重载，没有默认参数，也没有继承，没有泛型，没有异常，没有宏，没有函数修饰，更没有线程局部存储。因为 Go 语言倡导成熟和稳定，并且保证向后兼容。</p><h2 id="2-基础"><a href="#2-基础" class="headerlink" title="2.基础"></a>2.基础</h2><h3 id="2-1-Hello-World"><a href="#2-1-Hello-World" class="headerlink" title="2.1 Hello, World"></a>2.1 Hello, World</h3><p>编写文件 <code>helloworld.go</code></p><figure class="highlight go"><table><tbody><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> main</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> <span class="string">"fmt"</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> {</span><br><span class="line">    fmt.Println(<span class="string">"Hello, 世界"</span>)</span><br><span class="line">}</span><br></pre></td></tr></tbody></table></figure><p>Go 是一门编译型语言，Go 语言的工具链将源代码及其依赖转换成计算机的机器指令。Go 语言提供的工具都通过一个单独的命令 <code>go</code> 调用，<code>go</code> 命令有一系列子命令。最简单的一个子命令就是 <code>run</code>。这个命令编译一个或多个以 <code>.go</code> 结尾的源文件，链接库文件，并运行最终生成的可执行文件。所以上面的程序也可以通过 <code>go run helloworld.go</code> 来运行。当然，也可以通过 <code>go build helloworld.go</code> 来编译，生成一个可执行二进制文件。</p><h3 id="2-2-代码格式"><a href="#2-2-代码格式" class="headerlink" title="2.2 代码格式"></a>2.2 代码格式</h3><p>Go 对于代码格式要求很严格，它提供 <code>gofmt</code> 工具把代码格式化为标准格式（Go 官方认定的一套代码格式），主流的 IDE 在保存 Go 源码时都会自动应用 <code>gofmt</code>，这使得 Go 源码的格式非常统一，Go 开发者不会为代码格式而烦恼。如果格式不对，编译时会报错。</p><blockquote><p>以法令方式规定标准的代码格式可以避免无尽的无意义的琐碎争执。</p></blockquote><p>更重要的是，由于 Go 源码格式是唯一确定的，这使得开发者可以基于唯一格式做各种自动源码处理。</p><h3 id="2-3-命名风格"><a href="#2-3-命名风格" class="headerlink" title="2.3 命名风格"></a>2.3 命名风格</h3><h4 id="2-3-1-可见性"><a href="#2-3-1-可见性" class="headerlink" title="2.3.1 可见性"></a>2.3.1 可见性</h4><p>在 Go 语言中，名字开头字母的大小写决定了其在包外的可见性。如果一个名字是大写字母开头的，那么它将导出供包外访问。如：</p><figure class="highlight go"><table><tbody><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">type</span>(</span><br><span class="line">  People <span class="keyword">struct</span> {</span><br><span class="line">    Name <span class="keyword">string</span>	<span class="comment">// 名称在前，类型在后</span></span><br><span class="line">    age  <span class="keyword">int</span></span><br><span class="line">  }</span><br><span class="line">  house <span class="keyword">struct</span> {</span><br><span class="line">    name <span class="keyword">string</span></span><br><span class="line">  }</span><br><span class="line">)</span><br></pre></td></tr></tbody></table></figure><p>包名则习惯总是用小写字母。</p><h4 id="2-3-2-长度"><a href="#2-3-2-长度" class="headerlink" title="2.3.2 长度"></a>2.3.2 长度</h4><p>名字的长度没有逻辑限制，但 Go 语言风格倡导使用短小的命名，尤其对于局部变量而言。在 Go 源码中会经常出现 i, p 之类的短名字，只有当那些名字作用域较大，生命周期较长的变量才会使用有意义的长命名。</p><h3 id="2-4-声明和变量"><a href="#2-4-声明和变量" class="headerlink" title="2.4 声明和变量"></a>2.4 声明和变量</h3><p>可以使用 <code>var</code> 关键字来声明一个特定类型的变量，如下</p><figure class="highlight go"><table><tbody><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 标准</span></span><br><span class="line"><span class="keyword">var</span> num <span class="keyword">int</span> = <span class="number">10</span></span><br><span class="line"><span class="comment">// 省略初始化</span></span><br><span class="line"><span class="keyword">var</span> name <span class="keyword">string</span></span><br><span class="line"><span class="comment">// 省略类型，自动推断</span></span><br><span class="line"><span class="keyword">var</span> age = <span class="number">1</span></span><br></pre></td></tr></tbody></table></figure><h4 id="2-4-1-零值初始化机制"><a href="#2-4-1-零值初始化机制" class="headerlink" title="2.4.1 零值初始化机制"></a>2.4.1 零值初始化机制</h4><p>与 Java 语言不同，如果初始化表达式被省略，那么将使用零值初始化该变量。</p><ul><li>数值类型：0</li><li>布尔类型： false</li><li>字符串：””（空字符串）</li><li>接口或引用类型：nil</li></ul><p>零值初始化机制可以确保每个声明的变量总是有一个良好定义的值，因此 Go 语言中不存在未初始化的变量。</p><h4 id="2-4-2-简短变量声明"><a href="#2-4-2-简短变量声明" class="headerlink" title="2.4.2 简短变量声明"></a>2.4.2 简短变量声明</h4><p>在函数内部，有一种成为简短变量声明语句的形式可用于声明和初始化局部变量。</p><figure class="highlight go"><table><tbody><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">t := <span class="number">0.1</span></span><br><span class="line">a, b := <span class="string">"a"</span>, <span class="number">100</span></span><br></pre></td></tr></tbody></table></figure><p>因为简洁和灵活的特点，简短变量声明被广泛用于大部分的局部变量的声明和初始化。<code>var</code> 形式的声明语句往往是用于需要显式指定变量类型地方，或者因为变量稍后会被重新赋值而初始值无关紧要的地方。</p><p>对于已经声明过的变量，简短变量声明语句的行为变为赋值。</p><figure class="highlight go"><table><tbody><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">in, e := <span class="number">1</span>, <span class="number">2</span></span><br><span class="line"><span class="comment">// ...</span></span><br><span class="line">out, err := <span class="number">2</span>, <span class="number">3</span></span><br></pre></td></tr></tbody></table></figure><h3 id="2-5-指针"><a href="#2-5-指针" class="headerlink" title="2.5 指针"></a>2.5 指针</h3><p>是的，Go 语言中有指针。</p><h4 id="2-5-1-值拷贝"><a href="#2-5-1-值拷贝" class="headerlink" title="2.5.1 值拷贝"></a>2.5.1 值拷贝</h4><p>与 Java 语言不同，Go 中的函数入参、返回值都是值拷贝而非引用传递。所以，尽管 Go 的日常开发中较少需要使用指针，但参数值拷贝代价较大时，应当考虑使用指针。</p><figure class="highlight go"><table><tbody><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// https://play.golang.org/p/JgAMeQjXcfV</span></span><br><span class="line"><span class="keyword">package</span> main</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> (</span><br><span class="line">	<span class="string">"fmt"</span></span><br><span class="line">)</span><br><span class="line"></span><br><span class="line"><span class="keyword">type</span> people <span class="keyword">struct</span> {</span><br><span class="line">	name <span class="keyword">string</span></span><br><span class="line">}</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">rename</span><span class="params">(p people, name <span class="keyword">string</span>)</span></span> {</span><br><span class="line">	p.name = name</span><br><span class="line">}</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> {</span><br><span class="line">	<span class="keyword">var</span> p1 = people{<span class="string">"myk"</span>}</span><br><span class="line">	fmt.Println(p1.name)</span><br><span class="line">	rename(p1, <span class="string">"MYK"</span>)</span><br><span class="line">	fmt.Println(p1.name)</span><br><span class="line">}</span><br></pre></td></tr></tbody></table></figure><p>输出是：</p><figure class="highlight plain"><table><tbody><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">myk</span><br><span class="line">myk</span><br></pre></td></tr></tbody></table></figure><h4 id="2-5-2-示例：命令参数"><a href="#2-5-2-示例：命令参数" class="headerlink" title="2.5.2 示例：命令参数"></a>2.5.2 示例：命令参数</h4><p>指针是实现标准库中 flag 包的关键技术，它使用命令行参数来设置对应变量的值。</p><figure class="highlight go"><table><tbody><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// Echo4 prints its command-line arguments.</span></span><br><span class="line"><span class="keyword">package</span> main</span><br><span class="line"><span class="keyword">import</span> (</span><br><span class="line">  <span class="string">"flag"</span></span><br><span class="line">  <span class="string">"fmt"</span></span><br><span class="line">  <span class="string">"strings"</span></span><br><span class="line">)</span><br><span class="line"><span class="comment">// 返回指针</span></span><br><span class="line"><span class="keyword">var</span> n = flag.Bool(<span class="string">"n"</span>, <span class="literal">false</span>, <span class="string">"omit trailing newline"</span>)</span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> {</span><br><span class="line">  <span class="comment">// 解析命令行参数</span></span><br><span class="line">  flag.Parse()</span><br><span class="line">  fmt.Print(flag.Args())</span><br><span class="line">  <span class="keyword">if</span> !*n {</span><br><span class="line">  	fmt.Println()</span><br><span class="line">  }</span><br><span class="line">}</span><br></pre></td></tr></tbody></table></figure><p>调用 <code>flag.Bool</code> 函数会创建一个新的对应布尔型标志参数的变量。它有三个属性：第一个是的命令行标志参数的名字<code>n</code>，然后是该标志参数的默认值（这里是 false），最后是该标志参数对应的描述信息。上面的 <code>n</code> 是对应命令行标志参数变量的指针。</p><h3 id="2-6-多返回值"><a href="#2-6-多返回值" class="headerlink" title="2.6 多返回值"></a>2.6 多返回值</h3><p>在 Go 语言中，一个函数可以返回多个值。通常，Go 函数会返回两个值，一个是期望的返回值，另一个是函数出错时的错误信息。</p><figure class="highlight go"><table><tbody><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">divide</span><span class="params">(a <span class="keyword">int</span>, b <span class="keyword">int</span>)</span><span class="params">(<span class="keyword">int</span>, error)</span></span>{</span><br><span class="line">  <span class="keyword">if</span> (b == <span class="number">0</span>){</span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>, errors.New(<span class="string">"xxxxx"</span>)</span><br><span class="line">  }<span class="keyword">else</span> {</span><br><span class="line">    <span class="keyword">return</span> a/b, <span class="literal">nil</span></span><br><span class="line">  }</span><br><span class="line">}</span><br><span class="line"></span><br><span class="line">r, err := divide(<span class="number">3</span>, <span class="number">1</span>)</span><br><span class="line"><span class="keyword">if</span> err != <span class="literal">nil</span> {</span><br><span class="line">  <span class="comment">// 错误处理</span></span><br><span class="line">}</span><br></pre></td></tr></tbody></table></figure><h3 id="2-7-Deferred-函数"><a href="#2-7-Deferred-函数" class="headerlink" title="2.7 Deferred 函数"></a>2.7 Deferred 函数</h3><p>在网络、IO 操作时，总要记得关闭资源。在 Java 中可以通过 try finally 块或 try with resources 来保证。而 Go 中可以通过独特的 defer 关键字实现。defer 语句执行时，会将其后面的函数延迟执行。直到包含该 defer 语句的函数执行完毕时，这个函数才会被执行。可以在一个函数中执行多条 defer 语句，它们的执行顺序与声明顺序相反。</p><figure class="highlight go"><table><tbody><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">do</span><span class="params">()</span></span>{</span><br><span class="line">	f, _ := os.Create(<span class="string">"/tmp/tmp.txt"</span>)</span><br><span class="line">	<span class="keyword">defer</span> f.Complete()</span><br><span class="line">  <span class="comment">// do something</span></span><br><span class="line">  f.Write(...)</span><br><span class="line">}</span><br></pre></td></tr></tbody></table></figure><h2 id="3-数组和切片"><a href="#3-数组和切片" class="headerlink" title="3.数组和切片"></a>3.数组和切片</h2><h3 id="3-1-数组"><a href="#3-1-数组" class="headerlink" title="3.1 数组"></a>3.1 数组</h3><p>数组是一个由固定长度的特定类型元素组成的序列，一个数组可以由零个或多个元素组成。因为数组的长度是固定的，因此在 Go 语言中很少直接使用数组。和数组对应的类型是Slice（切片），它是可以增长和收缩的动态序列，slice 功能也更灵活，但是要理解 slice工作原理的话需要先理解数组。</p><p>初始化数组：</p><figure class="highlight go"><table><tbody><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">a := [...]<span class="keyword">int</span>{<span class="number">1</span>, <span class="number">2</span>}</span><br></pre></td></tr></tbody></table></figure><p>初始化数组的索引顺序并不重要，可以如下初始：</p><figure class="highlight go"><table><tbody><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">type</span> Currency <span class="keyword">int</span></span><br><span class="line"><span class="keyword">const</span> (</span><br><span class="line">    USD Currency = <span class="literal">iota</span> <span class="comment">// 美元</span></span><br><span class="line">    EUR                 <span class="comment">// 欧元</span></span><br><span class="line">    GBP                 <span class="comment">// 英镑</span></span><br><span class="line">    RMB                 <span class="comment">// 人民币</span></span><br><span class="line">)</span><br><span class="line"></span><br><span class="line">symbol := [...]<span class="keyword">string</span>{USD: <span class="string">"$"</span>, EUR: <span class="string">"€"</span>, GBP: <span class="string">"￡"</span>, RMB: <span class="string">"￥"</span>}</span><br><span class="line"></span><br><span class="line">fmt.Println(RMB, symbol[RMB]) <span class="comment">// "3 ￥"</span></span><br></pre></td></tr></tbody></table></figure><p>也可以这样：</p><figure class="highlight go"><table><tbody><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">r := [...]<span class="keyword">int</span>{<span class="number">99</span>:<span class="number">-1</span>}</span><br></pre></td></tr></tbody></table></figure><p>未被初始化的元素都是零值。</p><p>由于 Go 的入参是值拷贝，所以传递大数组非常低效，并且函数内无法修改原数组。故时常显式地传入一个数组指针：</p><figure class="highlight go"><table><tbody><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 用于清空数组</span></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">zero</span><span class="params">(ptr *[32]<span class="keyword">byte</span>)</span></span> {</span><br><span class="line">    <span class="keyword">for</span> i := <span class="keyword">range</span> ptr {</span><br><span class="line">        ptr[i] = <span class="number">0</span></span><br><span class="line">    }</span><br><span class="line">}</span><br></pre></td></tr></tbody></table></figure><h3 id="3-1-切片"><a href="#3-1-切片" class="headerlink" title="3.1 切片"></a>3.1 切片</h3><p>Go 语言中数组长度也是类型的一部分，即 <code>[32]byte</code> 与 <code>[16]byte</code>是不同的类型，也就是说，上面这个函数不能接收 <code>*[16]byte</code> 类型的参数。同时，没有任何方法能添加或删除数组中的元素，所以数组使用起来并不便利。在实际开发中，一般使用 slice 来替代数组。</p><p>Slice（切片）代表变长的序列，序列中每个元素都有相同的类型。一个 slice 类型一般写作 <code>[]T</code>，其中T代表 slice 中元素的类型；slice 的语法和数组很像，只是没有固定长度而已。</p><figure class="highlight go"><table><tbody><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">s := []<span class="keyword">int</span>{<span class="number">1</span>, <span class="number">2</span>}</span><br></pre></td></tr></tbody></table></figure><p>数组和 slice 之间有着紧密的联系。一个 slice 是一个轻量级的数据结构，提供了访问数组子序列（或者全部）元素的功能，而且 slice 的底层确实引用一个数组对象。一个 slice 由三个部分构成：指针、长度和容量。指针指向第一个 slice 元素对应的底层数组元素的地址，要注意的是 slice 的第一个元素并不一定就是数组的第一个元素。长度对应 slice 中元素的数目；长度不能超过容量，容量一般是从 slice 的开始位置到底层数据的结尾位置。内置的 <code>len</code> 和 <code>cap</code> 函数分别返回 slice 的长度和容量。</p><p>多个slice之间可以共享底层的数据，并且引用的数组部分区间可能重叠。</p><h4 id="3-1-1-示例"><a href="#3-1-1-示例" class="headerlink" title="3.1.1 示例"></a>3.1.1 示例</h4><p>声明一个月份数组如：</p><figure class="highlight go"><table><tbody><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">months := [...]<span class="keyword">string</span>{<span class="number">1</span>: <span class="string">"January"</span>, <span class="comment">/* ... */</span>, <span class="number">12</span>: <span class="string">"December"</span>}</span><br></pre></td></tr></tbody></table></figure><p>使用切片操作：</p><figure class="highlight go"><table><tbody><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">Q2 := months[<span class="number">4</span>:<span class="number">7</span>]</span><br><span class="line">summer := months[<span class="number">6</span>:<span class="number">9</span>]</span><br><span class="line">fmt.Println(Q2)     <span class="comment">// ["April" "May" "June"]</span></span><br><span class="line">fmt.Println(summer) <span class="comment">// ["June" "July" "August"]</span></span><br></pre></td></tr></tbody></table></figure><p><img src="https://box.kancloud.cn/2016-01-10_5691fbe34a76f.png" alt="img"></p><p>如果切片操作超出 <code>cap(s)</code> 的上限将导致一个 panic 异常，但是超出 <code>len(s)</code> 则是意味着扩展了 slice，因为新 slice 的长度会变大：</p><figure class="highlight go"><table><tbody><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">fmt.Println(summer[:<span class="number">20</span>]) <span class="comment">// panic: out of range</span></span><br><span class="line"></span><br><span class="line">endlessSummer := summer[:<span class="number">5</span>] <span class="comment">// 扩展切片 (capacity 内)</span></span><br><span class="line">fmt.Println(endlessSummer)  <span class="comment">// "[June July August September October]"</span></span><br></pre></td></tr></tbody></table></figure><p>因为 slice 值包含指向第一个 slice 元素的指针，因此向函数传递 slice 将允许在函数内部修改底层数组的元素。换句话说，复制一个 slice 只是对底层的数组创建了一个新的 slice 别名。</p><h4 id="3-1-2-append"><a href="#3-1-2-append" class="headerlink" title="3.1.2 append"></a>3.1.2 append</h4><p>当 len&lt;cap 时，append 会在底层数组的基础上直接扩展切片；而 len=cap 时，append 后的切片长度会超出底层数组，这时一个新数组将被创建，返回的切片的底层数组将与原切片不同。所以，一般不能确认 append 返回的切片是否与原切片使用同样的底层数组，故通常将返回值复制给原切片。</p><figure class="highlight go"><table><tbody><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">endlessSummer = <span class="built_in">append</span>(endlessSummer, <span class="string">"No"</span>, <span class="string">"De"</span>, <span class="string">"??"</span>)</span><br></pre></td></tr></tbody></table></figure><h2 id="4-Goroutines-和-Channel"><a href="#4-Goroutines-和-Channel" class="headerlink" title="4.Goroutines 和 Channel"></a>4.Goroutines 和 Channel</h2><p>Go 语言中的并发程序可以用两种手段实现，本节主要介绍 goroutines 和 channel。</p><h3 id="4-1-Goroutines（协程）"><a href="#4-1-Goroutines（协程）" class="headerlink" title="4.1 Goroutines（协程）"></a>4.1 Goroutines（协程）</h3><p>Go 协程可以看作是轻量级线程。与线程相比，创建一个 Go 协程的成本很小。因此在 Go 应用中，常常会看到有数以千计的 Go 协程并发地运行。</p><blockquote><p>A <em>goroutine</em> is a lightweight thread managed by the Go runtime.</p></blockquote><h4 id="4-1-1-协程"><a href="#4-1-1-协程" class="headerlink" title="4.1.1 协程"></a>4.1.1 协程</h4><p>进程拥有代码和打开的文件资源、数据资源、独立的内存空间。</p><p>线程从属于进程，是程序的实际执行者。一个进程至少包含一个主线程，也可以有更多的子线程。线程拥有自己的栈空间。</p><p><img src="https://pic2.zhimg.com/80/v2-ae1d48089f6a4ff589bb5b948ee74a8d_1440w.jpg" alt="img"></p><p><strong>对操作系统来说，线程是最小的执行单元，进程是最小的资源管理单元。</strong></p><p><strong>协程，英文 Coroutines，是一种比线程更加轻量级的存在。</strong>正如一个进程可以拥有多个线程一样，一个线程也可以拥有多个协程。</p><p><img src="https://pic4.zhimg.com/80/v2-a31ca547de92311f644a4d25566eca1f_1440w.jpg" alt="img"></p><p>最重要的是，协程不是被操作系统内核所管理，而完全是由程序所控制（也就是在用户态执行）。</p><p>这样带来的好处就是性能得到了很大的提升，不会像线程切换那样消耗资源。</p><h4 id="4-1-2-Go-协程内部原理"><a href="#4-1-2-Go-协程内部原理" class="headerlink" title="4.1.2 Go 协程内部原理"></a>4.1.2 Go 协程内部原理</h4><p>综上可知，Go 协程实际上是由 Go 运行时管理的轻量级线程。Go 运行时中有一个专用的协程调度器 Go scheduler，更多可以参考 <a href="https://www.zhihu.com/question/20862617" target="_blank" rel="noopener">https://www.zhihu.com/question/20862617</a>.</p><p>Go 使用独立的调度器其中一个原因是 Go 的垃圾回收需要等待所有的 goroutine 停止，使得内存状态一致。而垃圾回收的时间点是不确定的，如果依赖操作系统的调度器，那么需要等待大量线程。</p><p>goroutines 在使用上非常简单，使用关键字 <code>go</code> 即可启动协程。例如：</p><figure class="highlight go"><table><tbody><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// https://play.golang.org/p/ZgRpYwet59D</span></span><br><span class="line"><span class="keyword">package</span> main</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> (</span><br><span class="line">	<span class="string">"fmt"</span></span><br><span class="line">)</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> {</span><br><span class="line">	<span class="keyword">go</span> say(<span class="string">"Hello World"</span>)</span><br><span class="line">}</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">say</span><span class="params">(s <span class="keyword">string</span>)</span></span> {</span><br><span class="line">	fmt.Println(s)</span><br><span class="line">}</span><br></pre></td></tr></tbody></table></figure><p>这个例子其实有些问题，实际运行时可能没有输出。我们将在后面 WaitGroup 的章节中完善它。</p><h5 id="4-1-2-1-调度模型简介"><a href="#4-1-2-1-调度模型简介" class="headerlink" title="4.1.2.1 调度模型简介"></a>4.1.2.1 调度模型简介</h5><p>Goroutines 能拥有强大的并发实现是通过 GPM 调度模型实现，下面就来解释下 goroutines的调度模型。</p><p><img src="https://images2018.cnblogs.com/blog/1075473/201807/1075473-20180704144900055-654632620.jpg" alt="img"></p><p>Go 的调度器内部有四个重要的结构：M，P，S，Sched，如上图所示（Sched未给出）</p><ul><li>M：M 代表内核级线程，一个 M 就是一个线程，goroutine 就是跑在 M 之上的；M 是一个很大的结构，里面维护小对象内存 cache（mcache）、当前执行的 goroutine、随机数发生器等等非常多的信息；</li><li>G：代表一个 goroutine，它有自己的栈，instruction pointer 和其他信息（正在等待的 channel 等等），用于调度；</li><li>P：P 全称是 Processor，处理器，它的主要用途就是用来执行 goroutine 的，所以它也维护了一个 goroutine 队列，里面存储了所有需要它来执行的 goroutine，是调度的上下文；</li><li>Sched：代表调度器，它维护有存储 M 和 G 的队列以及调度器的一些状态信息等。</li></ul><h5 id="4-1-2-2-调度实现"><a href="#4-1-2-2-调度实现" class="headerlink" title="4.1.2.2 调度实现"></a>4.1.2.2 调度实现</h5><p><img src="https://images2018.cnblogs.com/blog/1075473/201807/1075473-20180704160300058-287296807.jpg" alt="img"></p><p>从上图中看，有2个物理线程 M，每一个 M 都拥有一个处理器 P，每一个也都有一个正在运行的 goroutine。</p><p>P 的数量可以通过设置环境变量 <code>GOMAXPROCS</code> 或通过运行时函数 <code>GOMAXPROCS()</code> 来设置，它其实也就代表了真正的并发度，即有多少个goroutine 可以同时运行。</p><p>图中灰色的那些 goroutine 并没有运行，而是处于 ready 的就绪态，它们被排列在名为 runqueues 的列表中。P 维护着这个队列（称之为 runqueue），每有一个 go 语句被执行，runqueue 队列就在其末尾加入一个。</p><p>为了减少互斥锁的竞争，每个 P 都有自己的本地运行队列。旧版本的 Go 调度程序只有一个全局运行队列，该队列由互斥体保护。线程通常在等待互斥锁解除锁定时被阻塞，性能并不好。</p><p>为什么需要 P（上下文）？为什么不能直接把运行队列放到线程上，去掉上下文？因为如果正在运行的线程由于某种原因（常常是系统调用）需要阻塞，那么我们可以将上下文交给其它线程。</p><p>当一个 OS 线程 M0 陷入阻塞时（如下图)，P 转而在运行 M1，图中的 M1 可能是正被创建，或者从线程缓存中取出。</p><p><img src="https://images2018.cnblogs.com/blog/1075473/201807/1075473-20180704162532330-809705926.jpg" alt="img"></p><p>当 M0 返回时，它必须尝试取得一个 P 来运行goroutine，一般情况下，它会从其他的 OS 线程那里“偷”一个 P 过来，如果没有偷到的话，它就把 goroutine 放在一个 global runqueue 里，然后自己睡眠（放入线程缓冲里）。这个 global runqueue 是 P 在用完本地运行队列时从中提取的运行队列。所有的 P 也会周期性的检查 global runqueue 并运行其中的 goroutine，否则 global runqueue 上的 goroutine 永远无法执行。</p><p>以上处理系统调用的逻辑就是 Go 即使在 <code>GOMAXPROCS</code> 设为1时仍然运行多线程的原因 。</p><p>还有一种情况是 P 所分配的任务 G 很快就执行完了（分配不均），这就导致了这个处理器 P 很闲，但是其他的 P 还有任务，此时如果 global runqueue 没有任务 G 了，那么 P 不得不从其他的 P 里拿一些 G 来执行。一般来说，如果 P 从其他的 P 那里要拿任务的话，一般就拿 runqueue 的一半，这就确保了每个 OS 线程都能充分的使用，如下图：</p><p><img src="https://images2018.cnblogs.com/blog/1075473/201807/1075473-20180704164251684-1689850867.jpg" alt="img"></p><h4 id="4-1-3-WaitGroup"><a href="#4-1-3-WaitGroup" class="headerlink" title="4.1.3 WaitGroup"></a>4.1.3 WaitGroup</h4><p>前面提到的例子实际运行时可能会没有输出，这是因为协程执行前，主线程可能已经结束了。</p><p>Go sync 包下提供了 <code>sync.WaitGroup</code>，可以解决上述问题。修改程序如：</p><figure class="highlight go"><table><tbody><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// https://play.golang.org/p/m4DSi2cCxTE</span></span><br><span class="line"><span class="keyword">package</span> main</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> (</span><br><span class="line">	<span class="string">"fmt"</span></span><br><span class="line">	<span class="string">"sync"</span></span><br><span class="line">)</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> wg = sync.WaitGroup{}</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> {</span><br><span class="line">  <span class="comment">// 添加一个等待计数</span></span><br><span class="line">	wg.Add(<span class="number">1</span>)</span><br><span class="line">	<span class="keyword">go</span> say(<span class="string">"Hello World"</span>)</span><br><span class="line">  <span class="comment">// 阻塞等待</span></span><br><span class="line">	wg.Wait()</span><br><span class="line">}</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">say</span><span class="params">(s <span class="keyword">string</span>)</span></span> {</span><br><span class="line">	fmt.Println(s)</span><br><span class="line">  <span class="comment">// 减少一个等待计数</span></span><br><span class="line">	wg.Done()</span><br><span class="line">}</span><br></pre></td></tr></tbody></table></figure><h5 id="4-1-3-1-实现原理"><a href="#4-1-3-1-实现原理" class="headerlink" title="4.1.3.1 实现原理"></a>4.1.3.1 实现原理</h5><p>WaitGroup 的实现使用了信号量，其结构如下：</p><figure class="highlight go"><table><tbody><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">type</span> WaitGroup <span class="keyword">struct</span> {</span><br><span class="line">	<span class="comment">// 64-bit value: high 32 bits are counter, low 32 bits are waiter count.</span></span><br><span class="line">	<span class="comment">// 64-bit atomic operations require 64-bit alignment, but 32-bit</span></span><br><span class="line">	<span class="comment">// compilers do not ensure it. So we allocate 12 bytes and then use</span></span><br><span class="line">	<span class="comment">// the aligned 8 bytes in them as state, and the other 4 as storage</span></span><br><span class="line">	<span class="comment">// for the sema.</span></span><br><span class="line">	state1 [<span class="number">3</span>]<span class="keyword">uint32</span></span><br><span class="line">}</span><br></pre></td></tr></tbody></table></figure><p><img src="https://oscimg.oschina.net/oscnet/3d44fe27957013aa82eca2923cafe50d909.jpg" alt="3d44fe27957013aa82eca2923cafe50d909.jpg"></p><p>state1 是个长度为3的数组，其中包含了 state 和一个信号量，而 state 实际上是两个计数器：</p><ul><li>counter：当前还未执行结束的 goroutine 计数器</li><li>waiter count：等待 goroutine-group 结束的 goroutine 数量，即有多少个等候者</li><li>semaphore：信号量</li></ul><p>信号量是Unix系统提供的一种保护共享资源的机制，用于防止多个线程同时访问某个资源。可简单理解为信号量为一个数值：</p><ul><li>当信号量&gt;0时，表示资源可用，获取信号量时系统自动将信号量减1；</li><li>当信号量==0时，表示资源暂不可用，获取信号量时，当前线程会进入睡眠，当信号量为正时被唤醒；</li></ul><p>WaitGroup对外提供三个接口：</p><ul><li><p><code>Add(delta int)</code>: 将 delta 值加到 counter 中。当 counter = 0 时根据 waiter 数值释放等量的信号量，把等待的 goroutine 全部唤醒</p><figure class="highlight go"><table><tbody><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">func</span> <span class="params">(wg *WaitGroup)</span> <span class="title">Add</span><span class="params">(delta <span class="keyword">int</span>)</span></span> {</span><br><span class="line">    statep, semap := wg.state() <span class="comment">//获取state和semaphore地址指针</span></span><br><span class="line">    </span><br><span class="line">    state := atomic.AddUint64(statep, <span class="keyword">uint64</span>(delta)&lt;&lt;<span class="number">32</span>) <span class="comment">//把delta左移32位累加到state，即累加到counter中</span></span><br><span class="line">    v := <span class="keyword">int32</span>(state &gt;&gt; <span class="number">32</span>) <span class="comment">//获取counter值</span></span><br><span class="line">    w := <span class="keyword">uint32</span>(state)      <span class="comment">//获取waiter值</span></span><br><span class="line">    </span><br><span class="line">    <span class="keyword">if</span> v &lt; <span class="number">0</span> {              <span class="comment">//经过累加后counter值变为负值，panic</span></span><br><span class="line">        <span class="built_in">panic</span>(<span class="string">"sync: negative WaitGroup counter"</span>)</span><br><span class="line">    }</span><br><span class="line"></span><br><span class="line">    <span class="comment">//经过累加后，此时，counter &gt;= 0</span></span><br><span class="line">    <span class="comment">//如果counter为正，说明不需要释放信号量，直接退出</span></span><br><span class="line">    <span class="comment">//如果waiter为零，说明没有等待者，也不需要释放信号量，直接退出</span></span><br><span class="line">    <span class="keyword">if</span> v &gt; <span class="number">0</span> || w == <span class="number">0</span> {</span><br><span class="line">        <span class="keyword">return</span></span><br><span class="line">    }</span><br><span class="line"></span><br><span class="line">    <span class="comment">//此时，counter一定等于0，而waiter一定大于0（内部维护waiter，不会出现小于0的情况），</span></span><br><span class="line">    <span class="comment">//先把counter置为0，再释放waiter个数的信号量</span></span><br><span class="line">    *statep = <span class="number">0</span></span><br><span class="line">    <span class="keyword">for</span> ; w != <span class="number">0</span>; w-- {</span><br><span class="line">        runtime_Semrelease(semap, <span class="literal">false</span>) <span class="comment">//释放信号量，执行一次释放一个，唤醒一个等待者</span></span><br><span class="line">    }</span><br><span class="line">}</span><br></pre></td></tr></tbody></table></figure></li><li><p><code>Wait()</code>： waiter 递增1，并阻塞等待信号量 semaphore</p><figure class="highlight go"><table><tbody><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">func</span> <span class="params">(wg *WaitGroup)</span> <span class="title">Wait</span><span class="params">()</span></span> {</span><br><span class="line">    statep, semap := wg.state() <span class="comment">//获取state和semaphore地址指针</span></span><br><span class="line">    <span class="keyword">for</span> {</span><br><span class="line">        state := atomic.LoadUint64(statep) <span class="comment">//获取state值</span></span><br><span class="line">        v := <span class="keyword">int32</span>(state &gt;&gt; <span class="number">32</span>)            <span class="comment">//获取counter值</span></span><br><span class="line">        w := <span class="keyword">uint32</span>(state)                 <span class="comment">//获取waiter值</span></span><br><span class="line">        <span class="keyword">if</span> v == <span class="number">0</span> {                        <span class="comment">//如果counter值为0，说明所有goroutine都退出了，不需要待待，直接返回</span></span><br><span class="line">            <span class="keyword">return</span></span><br><span class="line">        }</span><br><span class="line">        </span><br><span class="line">        <span class="comment">// 使用CAS（比较交换算法）累加waiter，累加可能会失败，失败后通过for loop下次重试</span></span><br><span class="line">        <span class="keyword">if</span> atomic.CompareAndSwapUint64(statep, state, state+<span class="number">1</span>) {</span><br><span class="line">            runtime_Semacquire(semap) <span class="comment">//累加成功后，等待信号量唤醒自己</span></span><br><span class="line">            <span class="keyword">return</span></span><br><span class="line">        }</span><br><span class="line">    }</span><br><span class="line">}</span><br></pre></td></tr></tbody></table></figure></li><li><p><code>Done()</code>： counter 递减1，按照 waiter 数值释放相应次数信号量</p><figure class="highlight go"><table><tbody><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">func</span> <span class="params">(wg *WaitGroup)</span> <span class="title">Done</span><span class="params">()</span></span> {</span><br><span class="line">	wg.Add(<span class="number">-1</span>)</span><br><span class="line">}</span><br></pre></td></tr></tbody></table></figure></li></ul><h3 id="4-2-Channel"><a href="#4-2-Channel" class="headerlink" title="4.2 Channel"></a>4.2 Channel</h3><p>goroutine 本质上是协程，协程之间如何通信呢？</p><blockquote><p><em>Do not communicate by sharing memory; instead, share memory by communicating.</em></p><p>不要通过共享内存来通信，要通过通信来共享内存。</p></blockquote><p>Java，C++ 等语言使用的传统线程模型要求开发者在不同线程中通过共享内存通信。通常，共享数据结构通过锁来保护，线程通过争夺锁的方式来访问数据。</p><p>而 Go 的并发原语——goroutines 和 channels 提供了一种优雅而独特的方法。Go 鼓励使用 channel 在 goroutine 之间传递对数据的引用，而不是显式地使用锁来调解对共享数据的访问。</p><h4 id="4-2-1-使用"><a href="#4-2-1-使用" class="headerlink" title="4.2.1 使用"></a>4.2.1 使用</h4><p>每个 channel 都有一个特殊的类型，也就是 channels 可发送数据的类型。一个可以发送int 类型数据的 channel 一般写为 <code>chan int</code>。Channel 一般有带缓冲和不带缓冲两种类型：</p><figure class="highlight go"><table><tbody><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// buffered</span></span><br><span class="line">ch := <span class="built_in">make</span>(<span class="keyword">chan</span> <span class="keyword">int</span>, <span class="number">3</span>)</span><br><span class="line"><span class="comment">// unbuffered</span></span><br><span class="line">ch := <span class="built_in">make</span>(<span class="keyword">chan</span> <span class="keyword">int</span>)</span><br></pre></td></tr></tbody></table></figure><p>一个 channel 有发送和接受两个主要操作，都是通信行为。一个发送语句将一个值从一个 goroutine 通过 channel 发送到另一个执行接收操作的 goroutine。发送和接收两个操作都是用<code>&lt;-</code>运算符。在发送语句中，<code>&lt;-</code>运算符分割 channel 和要发送的值。在接收语句中，<code>&lt;-</code>运算符写在channel对象之前。一个不使用接收结果的接收操作也是合法的。</p><figure class="highlight go"><table><tbody><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">ch &lt;- x  <span class="comment">// a send statement</span></span><br><span class="line">x = &lt;-ch <span class="comment">// a receive expression in an assignment statement</span></span><br><span class="line">&lt;-ch     <span class="comment">// a receive statement; result is discarded</span></span><br></pre></td></tr></tbody></table></figure><p>Channel 还支持 close 操作，用于关闭 channel，随后对基于该 channel 的任何发送操作都将导致 panic 异常。对一个已经被 close 过的 channel 之行接收操作依然可以接受到之前已经成功发送的数据；如果 channel 中已经没有数据的话讲产生一个零值的数据。</p><p>使用内置的 <code>close</code> 函数就可以关闭一个 channel：</p><figure class="highlight go"><table><tbody><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">close</span>(ch)</span><br></pre></td></tr></tbody></table></figure><h4 id="4-2-2-无缓冲-Channels"><a href="#4-2-2-无缓冲-Channels" class="headerlink" title="4.2.2 无缓冲 Channels"></a>4.2.2 无缓冲 Channels</h4><p>一个基于无缓冲 Channels 的发送操作将导致发送者 goroutine 阻塞，直到另一个goroutine 在相同的 Channels 上执行接收操作，当发送的值通过 Channels 成功传输之后，两个 goroutine 可以继续执行后面的语句。反之，如果接收操作先发生，那么接收者 goroutine 也将阻塞，直到有另一个 goroutine 在相同的 Channels 上执行发送操作。</p><p>基于无缓冲 Channels 的发送和接收操作将导致两个 goroutine 做一次同步操作。因为这个原因，无缓冲 Channels 有时候也被称为同步 Channels。当通过一个无缓冲 Channels 发送数据时，接收者收到数据发生在唤醒发送者 goroutine 之前。<em>happens before</em> 是Go语言并发内存模型的一个关键术语。</p><p>使用同步 Channels 可以将上面的例子改造如下：</p><figure class="highlight go"><table><tbody><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// https://play.golang.org/p/scuDtKvwqGQ</span></span><br><span class="line"><span class="keyword">package</span> main</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> <span class="string">"fmt"</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> ch = <span class="built_in">make</span>(<span class="keyword">chan</span> <span class="keyword">int</span>)</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> {</span><br><span class="line">	<span class="keyword">go</span> say(<span class="string">"Hello World"</span>)</span><br><span class="line">	&lt;-ch</span><br><span class="line">}</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">say</span><span class="params">(s <span class="keyword">string</span>)</span></span> {</span><br><span class="line">	fmt.Println(s)</span><br><span class="line">	ch &lt;- <span class="number">1</span></span><br><span class="line">}</span><br></pre></td></tr></tbody></table></figure><h4 id="4-2-3-缓冲-Channels"><a href="#4-2-3-缓冲-Channels" class="headerlink" title="4.2.3 缓冲 Channels"></a>4.2.3 缓冲 Channels</h4><p>带缓冲的 channel 内部持有一个元素队列。队列的最大容量是在调用make函数创建channel 时通过第二个参数指定的。其底层数据结构如下：</p><p><img src="https://img-blog.csdnimg.cn/20190307092857857.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3UwMTA4NTMyNjE=,size_16,color_FFFFFF,t_70" alt="img"></p><h4 id="4-2-4-sends-and-receives"><a href="#4-2-4-sends-and-receives" class="headerlink" title="4.2.4 sends and receives"></a>4.2.4 sends and receives</h4><p>不同goroutine在channel上面进行读写时，涉及到的过程比较复杂，比如下图：</p><p><img src="https://img-blog.csdnimg.cn/20190105122332181.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3UwMTA4NTMyNjE=,size_16,color_FFFFFF,t_70" alt="在这里插入图片描述"></p><p>上图中G1会往channel里面写入数据，G2会从channel里面读取数据。</p><p>G1作用于底层hchan的流程如下图：</p><p><img src="https://img-blog.csdnimg.cn/20190105123351626.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3UwMTA4NTMyNjE=,size_16,color_FFFFFF,t_70" alt="在这里插入图片描述"></p><ol><li>先获取全局锁；</li><li>然后enqueue元素(通过移动拷贝的方式)；</li><li>释放锁；</li></ol><p>G2读取时候作用于底层数据结构流程如下图所示：</p><p><img src="https://img-blog.csdnimg.cn/20190105123802359.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3UwMTA4NTMyNjE=,size_16,color_FFFFFF,t_70" alt="在这里插入图片描述"></p><ol><li>先获取全局锁；</li><li>然后dequeue元素(通过移动拷贝的方式)；</li><li>释放锁；</li></ol><p>上面的读写思路其实很简单，除了hchan数据结构外，不要通过共享内存去通信；而是通过通信(复制)实现共享内存。</p><h4 id="4-2-5-阻塞与调度"><a href="#4-2-5-阻塞与调度" class="headerlink" title="4.2.5 阻塞与调度"></a>4.2.5 阻塞与调度</h4><p>当向满 channel 写入数据时，发生了什么呢？</p><p><img src="https://img-blog.csdnimg.cn/20190105143018955.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3UwMTA4NTMyNjE=,size_16,color_FFFFFF,t_70" alt="在这里插入图片描述"></p><p>上图流程大概如下：</p><p>当前 goroutine（G1）会调用<code>gopark</code>函数，将当前协程置为 waiting 状态；<br>将M和G1绑定关系断开；<br>scheduler 会调度另外一个就绪态的 goroutine 与 M 建立绑定关系，然后 M 会运行另外一个 G。<br>所以整个过程中，OS thread会一直处于运行状态，不会因为协程G1的阻塞而阻塞。最后当前的G1的引用会存入 channel 的 sender 队列（队列元素是持有G1的sudog）。</p><p>那么 blocked 的G1怎么恢复呢？当有一个 receiver 接收 channel 数据的时候，会恢复 G1。实际上 hchan 数据结构也存储了 channel 的 sender 和 receiver 的等待队列。数据原型如下：</p><p><img src="https://img-blog.csdnimg.cn/20190307093911177.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3UwMTA4NTMyNjE=,size_16,color_FFFFFF,t_70" alt="在这里插入图片描述"></p><p>总结一下 Channel 的内部结构如下图：</p><p><img src="https://i6448038.github.io/img/channel/hchan.png" alt="img"></p><ul><li><code>buf</code>是有缓冲的channel所特有的结构，用来存储缓存数据。是个循环链表</li><li><code>sendx</code>和<code>recvx</code>用于记录<code>buf</code>这个循环链表中的发送或者接收的index</li><li><code>lock</code>是个互斥锁。</li><li><code>recvq</code>和<code>sendq</code>分别是接收(&lt;-channel)或者发送(channel &lt;- xxx)的goroutine抽象出来的结构体(sudog)的队列。是个双向链表</li></ul><h3 id="4-3-Context"><a href="#4-3-Context" class="headerlink" title="4.3 Context"></a>4.3 Context</h3><p>上下文 <a href="https://github.com/golang/go/blob/df2999ef43ea49ce1578137017949c0ee660608a/src/context/context.go#L62-L154" target="_blank" rel="noopener"><code>context.Context</code></a> 是用来设置截止日期、同步信号，传递请求相关值的结构体。上下文与 Goroutine 有比较密切的关系。<a href="https://github.com/golang/go/blob/df2999ef43ea49ce1578137017949c0ee660608a/src/context/context.go#L62-L154" target="_blank" rel="noopener"><code>context.Context</code></a> 是 Go 语言中独特的设计，在其他编程语言中我们很少见到类似的概念。</p><h4 id="4-3-1-设计原理"><a href="#4-3-1-设计原理" class="headerlink" title="4.3.1 设计原理"></a>4.3.1 设计原理</h4><p>在 Go 服务器中，每个传入的请求都在其自己的 goroutine 中处理。请求处理程序通常会启动其他 goroutine 来访问后端，如数据库和 RPC 服务。当请求被取消或超时时，处理该请求的所有 goroutine 都应快速退出，以便系统可以回收它们正在使用的任何资源。</p><p><img src="https://tva1.sinaimg.cn/large/00831rSTgy1gd7c035gouj30xc0aa74l.jpg" alt="golang-context-usage"></p><p>如下图，如果最上层的 goroutine 因某些原因失败时，下层的 goroutine 无法感知，将继续工作：</p><p><img src="https://tva1.sinaimg.cn/large/00831rSTgy1gd7c1p9jmij30xc0aadfz.jpg" alt="golang-without-context"></p><p>而通过传递 Context，可以让 goroutine 感知整体的状态。Context 代码结构如下：</p><figure class="highlight go"><table><tbody><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">type</span> Context <span class="keyword">interface</span> {</span><br><span class="line">	Deadline() (deadline time.Time, ok <span class="keyword">bool</span>)</span><br><span class="line">	Done() &lt;-<span class="keyword">chan</span> <span class="keyword">struct</span>{}</span><br><span class="line">	Err() error</span><br><span class="line">	Value(key <span class="keyword">interface</span>{}) <span class="keyword">interface</span>{}</span><br><span class="line">}</span><br></pre></td></tr></tbody></table></figure><ol><li><code>Deadline</code>：返回 <a href="https://github.com/golang/go/blob/df2999ef43ea49ce1578137017949c0ee660608a/src/context/context.go#L62-L154" target="_blank" rel="noopener"><code>context.Context</code></a> 被取消的时间，也就是完成工作的截止日期；</li><li><code>Done</code>：返回一个 Channel，这个 Channel 会在当前工作完成或者上下文被取消之后关闭，多次调用 <code>Done</code> 方法会返回同一个 Channel；</li><li><code>Err</code>：返回 <code>context.Context</code> 结束的原因，它只会在 <code>Done</code> 返回的 Channel 被关闭时才会返回非空的值；<ol><li>如果 <a href="https://github.com/golang/go/blob/df2999ef43ea49ce1578137017949c0ee660608a/src/context/context.go#L62-L154" target="_blank" rel="noopener"><code>context.Context</code></a> 被取消，会返回 <code>Canceled</code> 错误；</li><li>如果 <a href="https://github.com/golang/go/blob/df2999ef43ea49ce1578137017949c0ee660608a/src/context/context.go#L62-L154" target="_blank" rel="noopener"><code>context.Context</code></a> 超时，会返回 <code>DeadlineExceeded</code> 错误；</li></ol></li><li><code>Value</code>：从 <a href="https://github.com/golang/go/blob/df2999ef43ea49ce1578137017949c0ee660608a/src/context/context.go#L62-L154" target="_blank" rel="noopener"><code>context.Context</code></a> 中获取键对应的值，对于同一个上下文来说，多次调用 <code>Value</code> 并传入相同的 <code>Key</code> 会返回相同的结果，该方法可以用来传递请求特定的数据；</li></ol><h4 id="4-3-2-使用"><a href="#4-3-2-使用" class="headerlink" title="4.3.2 使用"></a>4.3.2 使用</h4><p>下面的示例演示了如何使用一个带超时的 Context：</p><figure class="highlight go"><table><tbody><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// https://play.golang.org/p/WNVVur7OGgV</span></span><br><span class="line"><span class="keyword">package</span> main</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> (</span><br><span class="line">	<span class="string">"context"</span></span><br><span class="line">	<span class="string">"fmt"</span></span><br><span class="line">	<span class="string">"time"</span></span><br><span class="line">)</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> {</span><br><span class="line">	<span class="comment">// 构造一个超时时间为 1s 的 context</span></span><br><span class="line">	ctx, cancel := context.WithTimeout(context.Background(), <span class="number">1</span>*time.Second)</span><br><span class="line">	<span class="keyword">defer</span> cancel()</span><br><span class="line"></span><br><span class="line">	<span class="keyword">go</span> handle(ctx, <span class="number">500</span>*time.Millisecond)</span><br><span class="line"></span><br><span class="line">	&lt;-ctx.Done()</span><br><span class="line">	fmt.Println(<span class="string">"main: "</span>, ctx.Err())</span><br><span class="line">}</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">handle</span><span class="params">(ctx context.Context, duration time.Duration)</span></span> {</span><br><span class="line">  <span class="comment">// select 语句可以同时监听多个 Channel</span></span><br><span class="line">	<span class="keyword">select</span> {</span><br><span class="line">	<span class="keyword">case</span> &lt;-ctx.Done():</span><br><span class="line">		fmt.Println(<span class="string">"handle"</span>, ctx.Err())</span><br><span class="line">    <span class="comment">// time.After(durantion) 返回一个同步 Channel</span></span><br><span class="line">	<span class="keyword">case</span> &lt;-time.After(duration):</span><br><span class="line">		<span class="comment">// 模拟阻塞的耗时操作</span></span><br><span class="line">		fmt.Println(<span class="string">"处理耗时："</span>, duration)</span><br><span class="line">	}</span><br><span class="line">}</span><br></pre></td></tr></tbody></table></figure><h3 id="4-4-实践"><a href="#4-4-实践" class="headerlink" title="4.4 实践"></a>4.4 实践</h3><p>下面是一段示例代码，其主要逻辑包含两个并行任务：</p><figure class="highlight go"><table><tbody><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">func</span> <span class="params">(agent *Agent)</span> <span class="title">doSpecialize</span><span class="params">(ctx context.Context, req *SpecializeRequest)</span> <span class="title">error</span></span> {</span><br><span class="line">	agent.logger.Info(<span class="string">"specialization begin..."</span>)</span><br><span class="line"></span><br><span class="line">  <span class="comment">// 创建一个可取消的 context</span></span><br><span class="line">	agentCtx, cancel := context.WithCancel(ctx)</span><br><span class="line">	<span class="keyword">defer</span> cancel()</span><br><span class="line">  <span class="comment">// 创建一个 task channel</span></span><br><span class="line">	taskCh := <span class="built_in">make</span>(<span class="keyword">chan</span> error, <span class="number">2</span>)</span><br><span class="line"></span><br><span class="line">	<span class="keyword">go</span> <span class="function"><span class="keyword">func</span><span class="params">()</span></span> {</span><br><span class="line">		<span class="keyword">if</span> err := agent.fetcher.Fetch(agentCtx, req.Url, req.FileName); err != <span class="literal">nil</span> {</span><br><span class="line">			taskCh &lt;- err</span><br><span class="line">      <span class="comment">// 如果出错，则取消 context</span></span><br><span class="line">			cancel()</span><br><span class="line">		} <span class="keyword">else</span> {</span><br><span class="line">			taskCh &lt;- <span class="literal">nil</span></span><br><span class="line">		}</span><br><span class="line">	}()</span><br><span class="line">	<span class="keyword">go</span> <span class="function"><span class="keyword">func</span><span class="params">()</span></span> {</span><br><span class="line">		<span class="keyword">if</span> err := ioutil.WriteFile(appKeyFilePath, []<span class="keyword">byte</span>(req.AppKey), <span class="number">0644</span>); err != <span class="literal">nil</span> {</span><br><span class="line">			taskCh &lt;- err</span><br><span class="line">      <span class="comment">// 如果出错，则取消 context</span></span><br><span class="line">			cancel()</span><br><span class="line">		} <span class="keyword">else</span> {</span><br><span class="line">			taskCh &lt;- <span class="literal">nil</span></span><br><span class="line">		}</span><br><span class="line">	}()</span><br><span class="line"></span><br><span class="line">	<span class="comment">// wait for the sub task, return error if any</span></span><br><span class="line">	taskCount := <span class="number">2</span></span><br><span class="line">  <span class="comment">// 迭代 task channel</span></span><br><span class="line">	<span class="keyword">for</span> c := <span class="keyword">range</span> taskCh {</span><br><span class="line">		<span class="keyword">if</span> c != <span class="literal">nil</span> {</span><br><span class="line">      <span class="comment">// 如果有错误，则立即返回错误</span></span><br><span class="line">			<span class="keyword">return</span> c</span><br><span class="line">		} <span class="keyword">else</span> {</span><br><span class="line">			taskCount--</span><br><span class="line">		}</span><br><span class="line">		<span class="keyword">if</span> taskCount &lt;= <span class="number">0</span> {</span><br><span class="line">			<span class="keyword">break</span></span><br><span class="line">		}</span><br><span class="line">	}</span><br><span class="line"></span><br><span class="line">	agent.logger.Info(<span class="string">"specialization done."</span>)</span><br><span class="line">	<span class="keyword">return</span> <span class="literal">nil</span></span><br><span class="line">}</span><br></pre></td></tr></tbody></table></figure><h2 id="5-依赖管理"><a href="#5-依赖管理" class="headerlink" title="5.依赖管理"></a>5.依赖管理</h2><p>相比 Java，Go 没有类似 Maven，Gradle 这样优秀的依赖管理系统，其依赖管理非常粗放，<del>参考 C</del>。</p><p>虽然可以通过 <code>go get xxx</code> 来下载依赖，但它做的仅仅是帮你把源码下载到相关目录，并不提供类似于版本控制、依赖合并等高级功能。所以很多 Go 项目在使用依赖时仅仅是将依赖下载到 <code>GOPATH</code> 下，供 <code>go build</code> 时链接。</p><p>归根结底，造成这种情况的原因可能是 Go 项目结构太过自由，缺少模块的概念。</p><p>但 Go 1.11版本开始添加了对模块的实验性支持，1.12版本删除了对 <code>GOPATH</code> 的支持。使得 Go 终于有了像样的依赖管理。</p><p>可以用环境变量 <code>GO111MODULE</code> 开启或关闭模块支持，它有三个可选值：<code>off</code>、<code>on</code>、<code>auto</code>，默认值是 <code>auto</code>。</p><ul><li><code>GO111MODULE=off</code> 无模块支持，go 会从 GOPATH 和 vendor 文件夹寻找包。</li><li><code>GO111MODULE=on</code> 模块支持，go 会忽略 GOPATH 和 vendor 文件夹，只根据 <code>go.mod</code> 下载依赖。</li><li><code>GO111MODULE=auto</code> 在 <code>$GOPATH/src</code> 外面且根目录有 <code>go.mod</code> 文件时，开启模块支持。</li></ul><h3 id="5-1-模块定义"><a href="#5-1-模块定义" class="headerlink" title="5.1 模块定义"></a>5.1 模块定义</h3><p>每个模块化的项目根目录下都应该有一个 <code>go.mod</code> 文件，这个文件不用手写，可以通过</p><figure class="highlight shell"><table><tbody><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">go mod init xxx # xxx 是模块名</span><br></pre></td></tr></tbody></table></figure><p>生成。在项目目录下使用 <code>go get</code> 命令时会自动填写这个文件。</p><figure class="highlight go"><table><tbody><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">module agent</span><br><span class="line"></span><br><span class="line"><span class="keyword">go</span> <span class="number">1.13</span></span><br><span class="line"></span><br><span class="line">require (</span><br><span class="line">	github.com/natefinch/lumberjack v2<span class="number">.0</span><span class="number">.0</span>+incompatible</span><br><span class="line">	<span class="keyword">go</span>.uber.org/atomic v1<span class="number">.5</span><span class="number">.1</span> <span class="comment">// indirect</span></span><br><span class="line">	<span class="keyword">go</span>.uber.org/multierr v1<span class="number">.4</span><span class="number">.0</span> <span class="comment">// indirect</span></span><br><span class="line">	<span class="keyword">go</span>.uber.org/zap v1<span class="number">.13</span><span class="number">.0</span></span><br><span class="line">	golang.org/x/lint v0<span class="number">.0</span><span class="number">.0</span><span class="number">-20191125180803</span>-fdd1cda4f05f <span class="comment">// indirect</span></span><br><span class="line">	golang.org/x/net v0<span class="number">.0</span><span class="number">.0</span><span class="number">-20200114155413</span><span class="number">-6</span>afb5195e5aa</span><br><span class="line">	golang.org/x/tools v0<span class="number">.0</span><span class="number">.0</span><span class="number">-20200115044656</span><span class="number">-831f</span>db1e1868 <span class="comment">// indirect</span></span><br><span class="line">)</span><br></pre></td></tr></tbody></table></figure><p>上面是一个依赖列表，可以看到依赖中包含了依赖的版本号。</p><h3 id="5-2-版本规范"><a href="#5-2-版本规范" class="headerlink" title="5.2 版本规范"></a>5.2 版本规范</h3><p>Go 模块版本是有严格规范的，上面文件中很多依赖是不合规范的。详细规范可以参考<a href="https://blog.golang.org/v2-go-modules" target="_blank" rel="noopener">Go Modules: v2 and Beyond</a>。简单而言，当需要更新模块的大版本号时，应当更改模块名，以保证兼容性。调用方也需要同步修改引用路径为大版本号。</p><blockquote><p>每次大版本更新都会更新module的路径，也就是说在module的后面修改相应的版本号，所以后面的大版本路径一般会如下：</p><figure class="highlight go"><table><tbody><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">&gt;module xxx.com/arch/xxx.git/v3</span><br><span class="line">&gt; module xxx.com/arch/xxx.git/v4</span><br><span class="line">&gt; module xxx.com/arch/xxx.git/v5</span><br><span class="line">&gt;</span><br></pre></td></tr></tbody></table></figure></blockquote><blockquote><ul><li>如果遇上大版本更新，业务方接入时，需要修改自己的import路径</li><li>如果没有没有大版本更新，这不需要进行修改</li></ul></blockquote><h2 id="参考"><a href="#参考" class="headerlink" title="参考"></a>参考</h2><p>推荐两本书：</p><ol><li><a href="http://www.kancloud.cn:8080/hartnett/gopl-zh" target="_blank" rel="noopener">Go 语言圣经</a></li><li><a href="https://draveness.me/golang/" target="_blank" rel="noopener">Go 语言设计与实现</a></li><li><a href="https://golang.org/doc/effective_go.html" target="_blank" rel="noopener">Effective Go</a></li></ol><p>参考文章：</p><ol><li><p><a href="https://www.cnblogs.com/wdliu/p/9272220.html" target="_blank" rel="noopener">go语言之行–golang核武器goroutine调度原理、channel详解</a></p></li><li><p><a href="https://zhuanlan.zhihu.com/p/74047342" target="_blank" rel="noopener">Golang协程详解和应用</a></p></li><li><p><a href="http://morsmachine.dk/go-scheduler" target="_blank" rel="noopener">The Go scheduler</a></p></li><li><p><a href="https://taohuawu.club/high-performance-implementation-of-goroutine-pool" target="_blank" rel="noopener">Goroutine 并发调度模型深度解析之手撸一个高性能 goroutine 池</a></p></li><li><p><a href="https://my.oschina.net/renhc/blog/2249061" target="_blank" rel="noopener">Go WaitGroup实现原理</a></p></li><li><p><a href="https://www.cnblogs.com/RyuGou/p/10776565.html" target="_blank" rel="noopener">图解Go的channel底层原理</a></p></li><li><p><a href="https://blog.csdn.net/u010853261/article/details/85231944" target="_blank" rel="noopener">Golang-Channel原理解析</a></p></li><li><p><a href="https://golang.org/doc/" target="_blank" rel="noopener">https://golang.org/doc/</a></p></li><li><p><a href="https://blog.golang.org/" target="_blank" rel="noopener">https://blog.golang.org/</a></p></li><li><p><a href="https://blog.golang.org/v2-go-modules" target="_blank" rel="noopener">Go Modules: v2 and Beyond</a></p></li><li><p><a href="https://blog.cyeam.com/go/2019/03/12/go-version" target="_blank" rel="noopener">Go module 如何发布 v2 及以上版本？</a></p></li><li><p><a href="https://blog.golang.org/context" target="_blank" rel="noopener">Go Concurrency Patterns: Context</a></p></li><li><p><a href="https://blog.golang.org/codelab-share" target="_blank" rel="noopener">Share Memory By Communicating</a></p></li></ol></div><footer class="post-footer"><div class="post-tags"> <a href="/tags/Go/" rel="tag"># Go</a></div><div class="post-nav"><div class="post-nav-next post-nav-item"><a href="/开发/43a5efe7.html" rel="next" title="Spring CGLIB 动态代理子类导致的注解丢失"><i class="fa fa-chevron-left"></i> Spring CGLIB 动态代理子类导致的注解丢失</a></div><span class="post-nav-divider"></span><div class="post-nav-prev post-nav-item"></div></div></footer></div></article></div></div><div class="comments" id="comments"></div></div><div class="sidebar-toggle"><div class="sidebar-toggle-line-wrap"><span class="sidebar-toggle-line sidebar-toggle-line-first"></span><span class="sidebar-toggle-line sidebar-toggle-line-middle"></span><span class="sidebar-toggle-line sidebar-toggle-line-last"></span></div></div><aside id="sidebar" class="sidebar"><div class="sidebar-inner"><ul class="sidebar-nav motion-element"><li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap"> 文章目录</li><li class="sidebar-nav-overview" data-target="site-overview-wrap"> 站点概览</li></ul><div class="site-overview-wrap sidebar-panel"><div class="site-overview"><div class="site-author motion-element" itemprop="author" itemscope="" itemtype="http://schema.org/Person"> <img class="site-author-image" itemprop="image" src="/images/blogAvatar.jpg" alt="moeyui"><p class="site-author-name" itemprop="name">moeyui</p><p class="site-description motion-element" itemprop="description">moeyui | moeyui's blog</p></div><nav class="site-state motion-element"><div class="site-state-item site-state-posts"> <a href="/archives/"><span class="site-state-item-count">39</span> <span class="site-state-item-name">日志</span></a></div><div class="site-state-item site-state-categories"> <a href="/categories/index.html"><span class="site-state-item-count">6</span> <span class="site-state-item-name">分类</span></a></div><div class="site-state-item site-state-tags"> <a href="/tags/index.html"><span class="site-state-item-count">36</span> <span class="site-state-item-name">标签</span></a></div></nav><div class="feed-link motion-element"><a href="/atom.xml" rel="alternate"><i class="fa fa-rss"></i> RSS</a></div><div class="links-of-author motion-element"><span class="links-of-author-item"><a href="https://github.com/moeyui1" title="GitHub → https://github.com/moeyui1" rel="noopener" target="_blank"><i class="fa fa-fw fa-github"></i> GitHub</a></span><span class="links-of-author-item"><a href="https://twitter.com/moeyui1" title="Twitter → https://twitter.com/moeyui1" rel="noopener" target="_blank"><i class="fa fa-fw fa-twitter"></i> Twitter</a></span></div></div></div><div class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active"><div class="post-toc"><div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#1-简介"><span class="nav-number">1.</span> <span class="nav-text">1.简介</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-基础"><span class="nav-number">2.</span> <span class="nav-text">2.基础</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#2-1-Hello-World"><span class="nav-number">2.1.</span> <span class="nav-text">2.1 Hello, World</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-2-代码格式"><span class="nav-number">2.2.</span> <span class="nav-text">2.2 代码格式</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-3-命名风格"><span class="nav-number">2.3.</span> <span class="nav-text">2.3 命名风格</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#2-3-1-可见性"><span class="nav-number">2.3.1.</span> <span class="nav-text">2.3.1 可见性</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#2-3-2-长度"><span class="nav-number">2.3.2.</span> <span class="nav-text">2.3.2 长度</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-4-声明和变量"><span class="nav-number">2.4.</span> <span class="nav-text">2.4 声明和变量</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#2-4-1-零值初始化机制"><span class="nav-number">2.4.1.</span> <span class="nav-text">2.4.1 零值初始化机制</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#2-4-2-简短变量声明"><span class="nav-number">2.4.2.</span> <span class="nav-text">2.4.2 简短变量声明</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-5-指针"><span class="nav-number">2.5.</span> <span class="nav-text">2.5 指针</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#2-5-1-值拷贝"><span class="nav-number">2.5.1.</span> <span class="nav-text">2.5.1 值拷贝</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#2-5-2-示例：命令参数"><span class="nav-number">2.5.2.</span> <span class="nav-text">2.5.2 示例：命令参数</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-6-多返回值"><span class="nav-number">2.6.</span> <span class="nav-text">2.6 多返回值</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-7-Deferred-函数"><span class="nav-number">2.7.</span> <span class="nav-text">2.7 Deferred 函数</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#3-数组和切片"><span class="nav-number">3.</span> <span class="nav-text">3.数组和切片</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#3-1-数组"><span class="nav-number">3.1.</span> <span class="nav-text">3.1 数组</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-1-切片"><span class="nav-number">3.2.</span> <span class="nav-text">3.1 切片</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#3-1-1-示例"><span class="nav-number">3.2.1.</span> <span class="nav-text">3.1.1 示例</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#3-1-2-append"><span class="nav-number">3.2.2.</span> <span class="nav-text">3.1.2 append</span></a></li></ol></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#4-Goroutines-和-Channel"><span class="nav-number">4.</span> <span class="nav-text">4.Goroutines 和 Channel</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#4-1-Goroutines（协程）"><span class="nav-number">4.1.</span> <span class="nav-text">4.1 Goroutines（协程）</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#4-1-1-协程"><span class="nav-number">4.1.1.</span> <span class="nav-text">4.1.1 协程</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#4-1-2-Go-协程内部原理"><span class="nav-number">4.1.2.</span> <span class="nav-text">4.1.2 Go 协程内部原理</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#4-1-2-1-调度模型简介"><span class="nav-number">4.1.2.1.</span> <span class="nav-text">4.1.2.1 调度模型简介</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#4-1-2-2-调度实现"><span class="nav-number">4.1.2.2.</span> <span class="nav-text">4.1.2.2 调度实现</span></a></li></ol></li><li class="nav-item nav-level-4"><a class="nav-link" href="#4-1-3-WaitGroup"><span class="nav-number">4.1.3.</span> <span class="nav-text">4.1.3 WaitGroup</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#4-1-3-1-实现原理"><span class="nav-number">4.1.3.1.</span> <span class="nav-text">4.1.3.1 实现原理</span></a></li></ol></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#4-2-Channel"><span class="nav-number">4.2.</span> <span class="nav-text">4.2 Channel</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#4-2-1-使用"><span class="nav-number">4.2.1.</span> <span class="nav-text">4.2.1 使用</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#4-2-2-无缓冲-Channels"><span class="nav-number">4.2.2.</span> <span class="nav-text">4.2.2 无缓冲 Channels</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#4-2-3-缓冲-Channels"><span class="nav-number">4.2.3.</span> <span class="nav-text">4.2.3 缓冲 Channels</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#4-2-4-sends-and-receives"><span class="nav-number">4.2.4.</span> <span class="nav-text">4.2.4 sends and receives</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#4-2-5-阻塞与调度"><span class="nav-number">4.2.5.</span> <span class="nav-text">4.2.5 阻塞与调度</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#4-3-Context"><span class="nav-number">4.3.</span> <span class="nav-text">4.3 Context</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#4-3-1-设计原理"><span class="nav-number">4.3.1.</span> <span class="nav-text">4.3.1 设计原理</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#4-3-2-使用"><span class="nav-number">4.3.2.</span> <span class="nav-text">4.3.2 使用</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#4-4-实践"><span class="nav-number">4.4.</span> <span class="nav-text">4.4 实践</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#5-依赖管理"><span class="nav-number">5.</span> <span class="nav-text">5.依赖管理</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#5-1-模块定义"><span class="nav-number">5.1.</span> <span class="nav-text">5.1 模块定义</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#5-2-版本规范"><span class="nav-number">5.2.</span> <span class="nav-text">5.2 版本规范</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#参考"><span class="nav-number">6.</span> <span class="nav-text">参考</span></a></li></ol></div></div></div></div></aside></div></main><footer id="footer" class="footer"><div class="footer-inner"><div class="copyright">© 2015 – <span itemprop="copyrightYear">2020</span><span class="with-love" id="animate"><i class="fa fa-user"></i></span> <span class="author" itemprop="copyrightHolder">moeyui</span></div><div class="powered-by">由 <a href="https://hexo.io" class="theme-link" rel="noopener" target="_blank">Hexo</a> 强力驱动 v3.9.0</div> <span class="post-meta-divider">|</span><div class="theme-info">主题 – <a href="https://theme-next.org" class="theme-link" rel="noopener" target="_blank">NexT.Gemini</a> v6.7.0</div></div></footer><div class="back-to-top"><i class="fa fa-arrow-up"></i></div></div><script src="//cdn1.lncld.net/static/js/3.11.1/av-min.js"></script><script src="//unpkg.com/valine/dist/Valine.min.js"></script><style>.copy-btn{display:inline-block;padding:6px 12px;font-size:13px;font-weight:700;line-height:20px;color:#333;white-space:nowrap;vertical-align:middle;cursor:pointer;background-color:#eee;background-image:linear-gradient(#fcfcfc,#eee);border:1px solid #d5d5d5;border-radius:3px;user-select:none;outline:0}.highlight-wrap .copy-btn{transition:opacity .3s ease-in-out;opacity:0;padding:2px 6px;position:absolute;right:4px;top:8px}.highlight-wrap .copy-btn:focus,.highlight-wrap:hover .copy-btn{opacity:1}.highlight-wrap{position:relative}</style><script src="/bundle.js"></script><script>"[object Function]"!==Object.prototype.toString.call(window.Promise)&&(window.Promise=null);var GUEST=["nick","mail","link"],guest="nick,mail,link";guest=guest.split(",").filter(function(e){return-1<GUEST.indexOf(e)}),new Valine({el:"#comments",verify:!1,notify:!1,appId:"Nk9tNzbllEl79DVtRiOuLmbm-gzGzoHsz",appKey:"uPzxSfSzF95Gav6vGx2dOhCq",placeholder:"Just go go",avatar:"retro",meta:guest,pageSize:"10",visitor:!0}),$(".highlight").each(function(e,t){var n=$("<div>").addClass("highlight-wrap");$(t).after(n),n.append($("<button>").addClass("copy-btn").append("复制").on("click",function(e){var t=$(this).parent().find(".code").find(".line").map(function(e,t){return $(t).text()}).toArray().join("\n"),n=document.createElement("textarea"),o=document.createRange(),i=window.getSelection(),a=window.pageYOffset||document.documentElement.scrollTop;n.style.top=a+"px",n.style.position="absolute",n.style.opacity="0",n.value=t,n.textContent=t,n.contentEditable=!0,n.readOnly=!1,document.body.appendChild(n),o.selectNode(n),i.removeAllRanges(),i.addRange(o),n.setSelectionRange(0,t.length);document.execCommand("copy");n.blur(),$(this).blur()})).on("mouseleave",function(e){var t=$(this).find(".copy-btn");setTimeout(function(){t.text("复制")},300)}).append(t)})</script></body></html>